import box/{condit,logger} shell/android

# Powered By Rikka (Shizuku & Sui)
# https://github.com/RikkaApps/Shizuku-API/tree/master/rish

target=$(getprop ro.build.version.sdk)
((target>=35))&&{
  [ -w "$RISH_SHIZUKU_DEX" ] && chmod -w "$RISH_SHIZUKU_DEX"
}

Has-Android-PkgName moe.shizuku.privileged.api||{
    Err "尚未安装 Shizuku，请先安装应用程序"
    exec am start \
    "https://shizuku.rikka.app/zh-hans/download" &>/dev/null
}

if ! Has-File "$RISH_SHIZUKU_DEX";then
    Err "找不到 $RISH_SHIZUKU_DEX, 请查看 Shizuku 应用程序中的教程"
    exec am start \
    "moe.shizuku.privileged.api/moe.shizuku.manager.MainActivity" &>/dev/null
fi

shift

rish_main_command(){
    RISH_APPLICATION_ID="com.termux" \
    /system/bin/app_process \
    -Djava.class.path="$RISH_SHIZUKU_DEX" \
    /system/bin \
    --nice-name=rish \
    rikka.shizuku.shell.ShizukuShellLoader \
    "$@"
}

case $1 in
    --info)
        RISH_RETURN="$(rish_main_command -c 'echo Pass' 2>&1)"
        case "${RISH_RETURN:-NONE_EXIT}" in
            'Request timeout'*)
                Err "与 Shizuku 的连接超时，可能有以下原因:"
                echo "  Shizuku 应用进程被 Android 限制"
                echo "  Shizuku 未曾打开过"
                echo "  Shizuku 未安装"
                Msg "可以尝试再次测试，如果未安装 Shizuku，请先安装并激活服务"
                exit 1
            ;;
            'Server is not running')
                Err "尚未激活 Shizuku 服务，请通过 ADB（有线/无线方式）激活服务"
                exit 1
            ;;
            'Permission denied')
                Err "Termux 尚未获得授权，请再次运行 RISH 后在 Shizuku 为其授权"
                exit 1
            ;;
            'NONE_EXIT')
                Err "空的异常退出"
                exit 1
            ;;
            'Pass')
                Msg "RISH 权限正常"
                exit 0
            ;;
        esac
    ;;
    *)
        rish_main_command "$@"
    ;;
esac